package com.bihua.iot.dynamicScript.nashorn;

import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;

import com.bihua.iot.dynamicScript.pool.Pool;
import com.bihua.iot.dynamicScript.pool.PoolUtil;

/**
 * @author bihua
 * @date 2023年06月20日 10:09
 */
public class NashornExecuteService {

    public static String executeDynamically(Long protocolId, String protocolContent, String mesBody) {
        Pool<CompiledScript> pool = PoolUtil.getPool(protocolId, protocolContent);
        CompiledScript compiledScript = pool.getResource();
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(compiledScript.getEngine().createBindings(), ScriptContext.ENGINE_SCOPE);
        compiledScript.getEngine().setContext(ctxt);
        try {
            compiledScript.eval(ctxt);
            String body = (String) ((Invocable) compiledScript.getEngine()).invokeFunction("convertToBody", mesBody);
            return body;
        } catch (ScriptException e) {
            e.printStackTrace();
        }catch (NoSuchMethodException e) {
            e.printStackTrace();
        }finally {
            if (compiledScript != null) {
                pool.returnResource(compiledScript);
            }
        }
        return null;
    }
}
